const app = getApp();
import {
  getStorage,
  setStorage
} from "../../../utils/localStorage"
import {
  myUserInfoUpdate,
  getUserInfo
} from "../../../api/my"
import {
  getWePhoneNumber
} from "../../../api/homePage"
import {
  baseUrl
} from "../../../api/request";
Page({
  data: {
    navData: {
      level: 2,
      title: '个人信息编辑'
    },
    editFlag: true,
    baseUrl: null,
    userInfo: {},
    imageList: [],
    url: baseUrl + '/common/upload',
    objDetail: {},
    navMargin: app.globalData.navHeight + app.globalData.navTop,
    ageArr: [
      "0-20",
      "20-40",
      "40-60",
      "60-80",
      "80-100",
      "100-120",
    ],
    width: 250, //宽度
    height: 250, //高度
    cropperState: false,
    //表单数据
    form: {},
  },
  onLoad(options) {
    this.setData({
      baseUrl: baseUrl,
      userInfo: getStorage('user'),
    });
    this.reset();

  },
  onReady() {

  },
  onShow() {

  },
  //初始化表单数据
  reset() {
    const _this = this.data;
    this.setData({
      form: {
        avatar: _this.userInfo.avatar || "",
        userName: _this.userInfo.userName || "",
        realName: _this.userInfo.realName || "",
        phoneNumber: _this.userInfo.phoneNumber || "",
        sex: _this.userInfo.sex || "",
        birthday: _this.userInfo.birthday || "",
        team: _this.userInfo.team || "",
        id: _this.userInfo.id,
        wxOpenid: getStorage("openId")
      }
    });
  },

  //修改用户头像
  editAvart() {
    wx.showActionSheet({
      itemList: ['相册', '相机'],
      success: res => {
        if (res.tapIndex === 0) {
          this.upload('相册');
        } else if (res.tapIndex === 1) {
          this.upload('相机');
        }
      },
      fail: err => {
        console.log('取消选择：打开相机或者相册', err);
      }
    })
  },


  //上传图片
  upload(val) {
    const sourceType = val === '相机' ? 'camera' : 'album';
    wx.chooseMedia({
      count: 1, //最多可以选择的图片张数
      mediaType: ['image'], //文件类型,image:图片，video:视频，mix:可同时选择图片和视频
      sizeType: ['original'], //所选的图片的尺寸,original:原图,compressed:压缩图  
      sourceType: [sourceType], //选择图片的来源:album:从相册选图,camera:使用相机
      success: res => {
        const {
          type,
          tempFiles
        } = res;
        //判断图片上传大小
        tempFiles.forEach(item => {
          wx.showLoading({
            title: '加载中'
          });
          this.setData({
            cropperState: true
          });
          this.cropper = this.selectComponent("#image-cropper");
          //开始裁剪
          this.setData({
            src: item.tempFilePath,
          });
        });
      },
      fail: err => {

      }
    })
  },


  cropperload(e) {
    console.log("cropper初始化完成");
  },
  loadimage(e) {
    console.log("图片加载完成", e.detail.path);
    // this.uploadFile(e.detail.path);
    wx.hideLoading();
    //重置图片角度、缩放、位置
    this.cropper.imgReset();
  },

  imageSubmit(e) {
    this.setData({
      "form.avatar": e.detail.path
    });
    let userInfo = getStorage("user");
    userInfo.avatar = e.detail.path;
    setStorage("user", userInfo);
    this.uploadFile(e.detail.path);
  },
  imageCancel(e) {
    this.setData({
      cropperState: false
    });
  },

  //上传图片到服务器
  uploadFile(file) {
    wx.showLoading();
    wx.uploadFile({
      filePath: file,
      name: "file",
      url: this.data.url,
      header: {
        "Content-Type": "multipart/form-data",
        "Authorization": "Bearer" + " " + getStorage('token')
      },
      formData: null,
      success: res => {
        const data = JSON.parse(res.data);
        if (data.code === 200) {
          this.setData({
            "form.avatar": this.data.baseUrl + data.fileName[0],
          });
          this.setData({
            cropperState: false
          });
          wx.hideLoading();
        }
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '上传图片失败' + err.msg,
          duration: 1000,
        });
        setTimeout(() => {
          this.setData({
            cropperState: false
          });
          wx.hideLoading();
        }, 1200)
      }
    })
  },

  clickcut(e) {
    console.log(e.detail);
    //点击裁剪框阅览图片
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url] // 需要预览的图片http链接列表
    })
  },

  //用户名bindinput事件
  nameInput(e) {
    const value = e.detail.value;
    this.setData({
      "form.userName": value,
    });
    // if (e.detail.cursor < 8) {

    // } else {
    //   wx.showToast({
    //     icon: 'none',
    //     title: '昵称字数最大为8位',
    //   });
    // };

  },

  //真实姓名change事件
  realNameInput(e) {
    const value = e.detail.value;
    this.setData({
      "form.realName": value,
    });
  },


  //手机号bindinput事件
  phoneInput(e) {
    const value = e.detail.value;
    this.setData({
      "form.phoneNumber": value,
    });
  },

  //年龄段bindinput事件
  srChange(e) {
    let index = Number(e.detail.value);
    this.setData({
      "form.birthday": this.data.ageArr[index],
    });
  },
  //性别change事件
  sexChange(e) {
    let value = e.detail.value;
    this.setData({
      "form.sex": value
    });
  },

  //团队bindinput事件
  teamInput(e) {
    const value = e.detail.value;
    this.setData({
      "form.team": value,
    });
  },
  //提交按钮点击事件
  async submit() {
    const that = this.data;
    if (!that.form.avatar) {
      wx.showToast({
        icon: 'none',
        title: '请上传用户头像',
        mask: true,
        duration: 2000
      });
    } else if (!that.form.userName) {
      wx.showToast({
        icon: 'none',
        title: '请输入昵称',
        mask: true,
        duration: 2000
      });
    } else if (!that.form.realName) {
      wx.showToast({
        icon: 'none',
        title: '请输入真实姓名',
        mask: true,
        duration: 2000
      });
    } else if (!that.form.phoneNumber) {
      wx.showToast({
        icon: 'none',
        title: '请绑定手机号',
        mask: true,
        duration: 2000
      });
    } else {
      myUserInfoUpdate(that.form).then(res => {
        if (res.data.code === 200) {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 2000
          });
          setTimeout(() => {
            let userInfo = getStorage("user");
            userInfo.userName = this.data.form.userName;
            userInfo.realName = this.data.form.realName;
            userInfo.birthday = this.data.form.birthday;
            userInfo.team = this.data.form.team;
            setStorage("user", userInfo);
            wx.navigateBack({
              delta: 1,
            });
          }, 2000);
        };
      });
    };
  },
  //获取用户信息
  // getWxUser() {
  //   let that = this.data;
  //   getUserInfo({
  //     id: that.userInfo.id
  //   }).then(res => {
  //     setStorage('user', res.data.data);
  //     this.setValue();
  //   });
  // },
  //获取用户手机号
  getPhoneNumber(e) {
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      getWePhoneNumber({ code: e.detail.code, wxOpenid: getStorage("openId") }).then(res => {
        let { code } = res.data;
        if (code === 200) {
          this.setData({
            "form.phoneNumber": res.data.data.phoneNumber
          });
          setStorage("user", res.data.data);
        };
      });
    };
  },

  //图片点击事件
  imgTap(e) {
    const url = e.currentTarget.dataset.url,
      urlList = url.split(",");
    app.imagePreview(url, urlList);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})